package com.garrett.demo.sys.dao;



import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.garrett.demo.sys.entity.Account;
import com.garrett.demo.sys.entity.SimsStudent;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

public class UserDaoTextImp implements UserDao{
    private static List<SimsStudent> students = new ArrayList<>();
    private static List<Account> accounts = new ArrayList<>();


    private static final String ACCOUNTPATH = "account.txt";
    private static final String STUDENTPATH = "sims_student.txt";


    /**
     * 初始化方法
     * 加载目标路径文件下的持久化数据
     * 判断文件是否存在不存在则创建
     */
    public static void init(){

        File accountFile = new File(ACCOUNTPATH);
        if (!accountFile.exists()){
            try {
                accountFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        File studentFile = new File(STUDENTPATH);
        if (!studentFile.exists()){
            try {
                studentFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        BufferedReader accountWriter = null;
        BufferedReader studentWriter = null;
        students.clear();
        accounts.clear();
        try {
            accountWriter = new BufferedReader(new FileReader(ACCOUNTPATH));
            studentWriter = new BufferedReader(new FileReader(STUDENTPATH));
            String line = accountWriter.readLine();
            while (line != null && line.length() > 0) {

                Account account = (Account) deserialize(line,Account.class);
                accounts.add(account);
                line = accountWriter.readLine();
            }
            line = studentWriter.readLine();
            while (line != null && line.length() > 0){

                SimsStudent student = (SimsStudent) deserialize(line,SimsStudent.class);
                students.add(student);
                line = studentWriter.readLine();
            }

        } catch (Exception  e) {
            e.printStackTrace();
        }finally {

            try {
                accountWriter.close();
                studentWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * json反序列化方法 将一个json的字符串 转换成目标对象
     * @param jsonStr
     * @param c
     * @return
     */
    private static Object deserialize(String jsonStr,Class c) {
        return JSONObject.toJavaObject(JSONObject.parseObject(jsonStr),c);
    }

    /**
     * 静态代码块 类加载时 调用初始化方法
     */
    static {
        init();
    }



    @Override
    public SimsStudent getStudentById(String stuId) {
        //断言参数不为空
        assert StringUtils.isNoneBlank(stuId);

        AtomicReference<SimsStudent> student = null;
        students.forEach(s->{
            if (stuId.equals(s.getStudentId())){
                student.set(s);
            }
        });

        return student.get();
    }

    /**
     * 根据登录账号获取用户信息
     *
     * @param account 账户名
     * @return 用户信息
     */
    @Override
    public Account getUserByAccount(String account) {
        assert StringUtils.isNoneBlank(account);

        Account a = null;
        for (int i = 0; i < accounts.size(); i++) {
            if (accounts.get(i).getAccount().equals(account)){
                a = accounts.get(i);
            }
        }

        return a;
    }

    /**
     * 注册账户信息
     *
     * @param account 账户
     */
    @Override
    public int addAccount(Account account) {

        FileWriter writer = null;
        try {
             writer = new  FileWriter(ACCOUNTPATH,true);
            writer.append(serialize(account) + "\n");
            return 1;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return 0;
    }



    @Override
    public int modifyAccount(Account account) {
        String id = account.getId();
        for (int i = 0; i < accounts.size(); i++) {
            if (accounts.get(i).getId().equals(id)){
                accounts.set(i,account);
                return 1;
            }
        }
        return 0;
    }

    /**
     * 添加学生信息
     *
     * @param student 学生信息
     */
    @Override
    public int createUser(SimsStudent student)   {
        FileWriter writer= null;
        try {



            writer = new FileWriter(STUDENTPATH,true);
            writer.append(serialize(student) + "\n");
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

    @Override
    public int delStudentInfo(String stuId) {
        return 0;
    }

    @Override
    public int modifyStudentInfo(SimsStudent student) {
        String id = student.getStudentId();
        for (int i = 0; i < students.size(); i++) {
            if (students.get(i).getStudentId().equals(id)){
                students.set(i,student);
                return 1;
            }
        }
        return 0;
    }
    @Override
    public void reWrite() {
        this.reWrite(accounts.toArray(new Account[accounts.size()]),students.toArray(new SimsStudent[students.size()]));
    }
    public  void reWrite(Account[] accounts ,SimsStudent[] students){
        FileWriter writers = null;
        FileWriter writera = null;
        try {
             writers = new FileWriter(STUDENTPATH);
             writera = new FileWriter(ACCOUNTPATH);

            for (int i = 0; i < accounts.length; i++) {
                writers.write(serialize(accounts[i]));
            }
            for (int i = 0; i < students.length; i++) {
                writera.write(serialize(students[i]));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                writers.close();
                writera.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private String serialize(Object o) {
        return JSON.toJSONString(o);
    }





    @Override
    public int delAccountById(String id) {


        for (int i = 0; i < accounts.size(); i++) {
            if (accounts.get(i).getId().equals(id)){
                accounts.remove(i);
            }
        }

        for (int i = 0; i < students.size(); i++) {
            if (students.get(i).getStudentId().equals(id)){
                students.remove(i);
            }
        }
        //重新写文件\
        Account[] arrAccount = new Account[accounts.size()];
        for (int i = 0; i < accounts.size(); i++) {
            arrAccount[i] = accounts.get(i);
        }
        SimsStudent[] arrStudent = new SimsStudent[students.size()];
        for (int i = 0; i < students.size(); i++) {
            arrStudent[i] = students.get(i);
        }
        this.reWrite(arrAccount,arrStudent);
        return 1;
    }

    @Override
    public Account[] getAllAccounts() {
        Account[] arr =  new Account[accounts.size()];
        for (int i = 0; i < accounts.size(); i++) {
            arr[i] = accounts.get(i);
        }
        return arr;
    }

    @Override
    public SimsStudent[] getAllStudent() {
        SimsStudent[] arr =  new SimsStudent[students.size()];
        for (int i = 0; i < students.size(); i++) {
            arr[i] = students.get(i);
        }
        return arr;
    }




}
